<template>
  <div class="app-container">
    <u-page title="活动管理">
      <div slot="header">
        <el-button type="primary" icon="el-icon-plus" @click="handleOpen(newForm)">
          {{ textMap['create'] }}
        </el-button>
      </div>

      <u-filtered>
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="listQuery.name" placeholder="活动名称" clearable style="width: 170px" />
          </el-form-item>
          <el-form-item label="活动类型" prop="type">
            <el-select v-model="listQuery.type" placeholder="请选择类型" class="disabled" clearable>
              <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="disabled">
            <u-status v-model="listQuery.disabled" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="hdlFilter">搜索</el-button>
          </el-form-item>
        </el-form>
      </u-filtered>

      <u-table
        :data="list"
        :loading="listLoading"
        :options="listOptions"
        :columns="columns"
        :pagination.sync="listQuery"
        :fetch="hdlList"
        @selection-change="hdlSelectChange"
      >
        <template v-slot:right>
          <el-table-column label="操作" align="center" fixed="right" width="160px">
            <template slot-scope="{ row }">
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" :disabled="!(row.type === 1)" @click="exportToExcel(row.id)">导出权益码</el-button>
              <el-button type="text" :disabled="!(row.type === 1)" @click="openStock(row)">库存调整</el-button>
              <el-button type="text" :disabled="!(row.type === 3)" @click="generateQRCode(row)">生成分享码</el-button>
              <!--              <el-button type="text" @click="hdlDelete(row.id, row.name)">删除</el-button>-->
            </template>
          </el-table-column>
        </template>
      </u-table>
    </u-page>
    <u-dialog :title="textMap[dialogStatus]" :show.sync="dialogFormVisible" width="980px" @confirm="dialogStatus==='create'? handleCreate():handleUpdate()">
      <el-form ref="dialogForm" :model="dataForm" :rules="rules" label-width="100px">
        <el-form-item label="活动时间" prop="validityDate">
          <u-date-time-picker v-model="dataForm.validityDate" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%" />
        </el-form-item>
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="dataForm.name" maxlength="20" show-word-limit placeholder="请输入活动名称" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-radio-group v-model="dataForm.type" :disabled="justRead">
            <el-radio-button :label="1">权益码</el-radio-button>
            <el-radio-button :label="2">口令码</el-radio-button>
            <el-radio-button :label="3">手机验证</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="dataForm.type===2" label="口令码" prop="cdkey">
          <el-input v-model="dataForm.cdkey" maxlength="20" placeholder="请输入口令码" :disabled="justRead" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item label="优惠券选择" prop="couponId">
          <num-coupon v-model="dataForm.couponId" multiple number @change="changeCouponList" />
        </el-form-item>
        <el-form-item label="总库存" prop="stock">
          <el-input v-model="dataForm.stock" placeholder="请输入库存" :disabled="dataForm.type===1&&justRead" style="width: 100%" />
        </el-form-item>
        <el-form-item label="每日限量" prop="dayLimit">
          <el-input v-model="dataForm.dayLimit" placeholder="请输入每日限量，不限制填0" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item v-if="dataForm.type===1" label="会员上限" prop="vipLimit">
          <el-input v-model="dataForm.vipLimit" placeholder="请输入会员参与上限，不限制填0" clearable style="width: 100%" />
        </el-form-item>
        <el-form-item label="使用场景" prop="parking_flag">
          <el-radio-group v-model="dataForm.parking_flag">
            <el-radio :label=false>普通场景</el-radio>
            <el-radio :label=true>消费领券</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跳转路径" prop="jumpMarker">
          <el-radio-group v-model="dataForm.jumpMarker">
            <el-radio :label="1">电商卡包</el-radio>
            <el-radio :label="2">停车场缴费</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="黑名单" prop="blacklist">
          <blacklist v-model="dataForm.blacklist" style="width: 100%" />
        </el-form-item>
      </el-form>
    </u-dialog>

    <u-dialog title="调整库存" :show.sync="dialogStockVisible" width="500px" @confirm="adjustStock()">
      <el-form ref="dialogForm" :model="stockForm" :rules="stockRules" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="stockForm.name" disabled style="width: 100%" />
        </el-form-item>
        <el-form-item label="调整方式" prop="type">
          <el-radio-group v-model="stockForm.type">
            <el-radio :label="1">调增</el-radio>
            <el-radio :label="2">调减</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="调整数量" prop="count">
          <el-input v-model="stockForm.count" placeholder="请输入调整数量" style="width: 100%" />
        </el-form-item>
      </el-form>
    </u-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import numCoupon from '@/components/coupon/numCoupon'
import blacklist from '@/components/module/blacklist'
export default {
  components: {
    numCoupon,
    blacklist
  },
  data() {
    return {
      api: this.$u.api.PluginsCdkeyActivity,
      cdkeyApi: this.$u.api.PluginsCdkey,
      dataForm: {
      },
      stockForm: {
      },
      listLoading: false,
      list: [],
      listOptions: {
        stripe: true
      },
      newForm: {
        type: 1,
        jumpMarker: 1,
        parking_flag: false
      },
      listQuery: {
        page: 1,
        pageSize: 10,
        totalCount: 1
      },
      textMap: {
        update: '编辑活动',
        create: '新建活动'
      },
      dialogFormVisible: false,
      dialogStockVisible: false,
      dialogStatus: '',
      rules: {
        validityDate: [
          { required: true, message: '活动时间必填', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '活动名称必填', trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '库存必填', trigger: 'blur' }
        ],
        cdkey: [
          { required: true, message: '口令码必填', trigger: 'blur' }
        ],
        couponId: [
          { required: true, message: '通联卡券必填', trigger: 'blur' }
        ],
        dayLimit: [
          { required: true, message: '限制次数必填，不限制填0', trigger: 'blur' }
        ],
        vipLimit: [
          { required: true, message: '限制次数必填，不限制填0', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '活动类型必选', trigger: 'change' }
        ],
        jumpMarker: [
          { required: true, message: '跳转路径必选', trigger: 'change' }
        ],
        parking_flag: [
          { required: true, message: '使用场景必选', trigger: 'change' }
        ]
      },
      stockRules: {
        count: [
          { required: true, message: '数量必填', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '活动类型必选', trigger: 'change' }
        ]
      },
      typeList: [
        {
          value: '',
          label: '全部'
        },
        {
          value: '1',
          label: '权益码'
        }, {
          value: '2',
          label: '口令码'
        }, {
          value: '3',
          label: '手机验证'
        }
      ],
      justRead: false,
      // 表格
      columns: [
        {
          prop: 'name',
          label: '活动名称'
        },
        {
          prop: 'type',
          label: '活动类型',
          render: (h, params) => {
            if (params.row.type === 1) {
              return h('el-tag', { props: { type: 'success' }}, '权益码')
            } else if (params.row.type === 2) {
              return h('el-tag', { props: { type: 'danger' }}, '口令码')
            } else {
              return h('el-tag', { props: { type: 'warning' }}, '手机验证')
            }
          }
        },
        {
          prop: 'validityDate',
          label: '活动时间',
          width: '180',
          render: (h, params) => {
            let { beginDate, endDate } = params.row
            if (!beginDate) {
              beginDate = '不限制'
            }
            if (!endDate) {
              endDate = '不限制'
            }
            return [
              h('el-tag', { props: { effect: 'plain' }}, '起始:' + beginDate),
              h('br'),
              h('el-tag', { props: { effect: 'plain' }}, '终止:' + endDate)
            ]
          }
        },
        {
          prop: 'couponList',
          label: '通联券',
          width: 180,
          render: (h, params) => {
            const { couponList } = params.row
            return h('div', couponList.map(item => h('div', [
              h('el-tag', item),
              h('br')
            ])))
          }
        },
        {
          prop: 'stock',
          label: '总库存'
        },
        {
          prop: 'vipLimit',
          label: '会员上限',
          formatter: (row) => {
            if (row.vipLimit === 0) {
              return '-'
            } else {
              return row.vipLimit
            }
          }
        },
        {
          prop: 'dayLimit',
          label: '日限量',
          formatter: (row) => {
            if (row.dayLimit === 0) {
              return '-'
            } else {
              return row.dayLimit
            }
          }
        },
        {
          prop: 'total',
          label: '已领取'
        },
        {
          prop: 'surplus',
          label: '剩余数量'
        },
        {
          prop: 'disabled',
          label: '状态',
          align: 'left',
          width: 70,
          switch: true,
          change: (event, row) => {
            this.hdlDisable(row, event, '[' + row.name + ']', '2')
          }
        }
      ]
    }
  },
  created() {
    this.hdlList()
  },
  methods: {
    // 打开库存调整
    openStock(row) {
      console.log('活动id:', row.id)
      this.stockForm.name = row.name
      this.stockForm.id = row.id
      this.dialogStockVisible = true
    },
    // 调整库存
    adjustStock() {
      // 效验数据格式
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.api.adjustStock({
            'id': this.stockForm.id,
            'type': this.stockForm.type,
            'count': this.stockForm.count
          }).then(() => {
            // 刷新数据列表
            this.hdlList()
            // 关闭弹窗状态
            this.dialogStockVisible = false
            // 通知信息
            this.$u.msg('库存调整成功')
          })
        }
      })
    },
    // 监听优惠券列表
    changeCouponList(list) {
      this.dataForm.couponChooseList = list
    },
    // 打开新建窗口
    handleOpen(newForm) {
      this.justRead = false
      this.hdlOpen(newForm)
    },
    // 新增事件
    handleCreate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginDate = validityDate[0]
        this.dataForm.endDate = validityDate[1]
      }
      this.hdlCreate()
    },
    // 打开修改弹窗
    handleEdit(row) {
      this.justRead = true
      const { beginDate, endDate } = row
      row.validityDate = []
      if (beginDate && endDate) {
        row.validityDate = [beginDate, endDate]
      }
      this.hdlEdit(row)
    },
    // 更新操作
    handleUpdate() {
      const { validityDate } = this.dataForm
      if (validityDate) {
        this.dataForm.beginDate = validityDate[0]
        this.dataForm.endDate = validityDate[1]
      }
      this.hdlUpdate()
    },
    // 生成分享码
    generateQRCode(row) {
      this.cdkeyApi.list({
        'activityId': row.id
      }).then(res => {
        const key = res.data[0].cdkey
        const qrData = 'https://csms.chiconysquare.net/mp/cdkey?cdkey='+key
        const qrCode = new QRCode(document.createElement('div'), {
          text: qrData,
          width: 200,
          height: 200,
        });
        const canvas = qrCode._el.firstChild;
        const imageUrl = canvas.toDataURL('image/png');
        const downloadLink = document.createElement('a');
        downloadLink.href = imageUrl;
        downloadLink.download = row.name+".png";
        downloadLink.click();
      })
    },
    // 导出权益码
    exportToExcel(activityId) {
      this.cdkeyApi.list({
        'activityId': activityId
      }).then(res => {
        const list = res.data
        // 业务数据处理
        list.forEach(item => {
          console.log(item.delFlag)
          this.$set(item, 'status', item.status === 0 ? '未领取' : '已领取')
          this.$set(item, 'updatedBy', item.delFlag ? item.updatedBy : '')
          this.$set(item, 'updatedAt', item.delFlag ? this.$u.timeFormat(item.updatedAt) : '')
          this.$set(item, 'delFlag', item.delFlag ? '失效' : '正常')
          this.$set(item, 'createdAt', item.createdAt ? this.$u.timeFormat(item.createdAt) : '')
        })
        console.log(list)
        // 表头&表数据
        const tHeader = ['权益码', '领取状态', '创建人', '创建时间', '禁用操作人', '禁用时间', '状态']
        const filterVal = ['cdkey', 'status', 'createdBy', 'createdAt', 'updatedBy', 'updatedAt', 'delFlag']
        const data = list.map(v => filterVal.map(j => {
          return v[j]
        }))
        this.$u.exports.excel('权益码', tHeader, data)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  .disabled {
    ::v-deep{
      .el-input{
        width: 140px;
      }
    }
  }
}
</style>

